﻿
using Castle.Core.Internal;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class OL_SalDailyInterfaceBusiness : Interface_BaseBusiness, IJob_Business, ITransientDependency
    {

        public List<OL_FilterDTO> Filters;
        public int NoQueryNum { get; set; }
        public Base_InterfaceOption queryOption { get; set; }
        public Base_InterfaceOption insertOption { get; set; }
        public Base_InterfaceOption upDateOption { get; set; }
        public Base_InterfaceOption deleteOption { get; set; }
        public OL_SalDailyInterfaceBusiness()
        {
            this.InterfaceName = "销售日报明细";
            //字段的映射关系
            tableField = GetMapField("addRow");
            //索引字段
            Keys = GetKeys("addRow");
            indexFields.Add(Keys.Where(X => X.Type == "K").First().Field);
            //查询过滤条件
            Filters = new List<OL_FilterDTO>();


            //数据库连接
            ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT  * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置
            insertOption = this.interfaceOption.Where(o => o.OperateType == "addRow").First();//新增API配置
            upDateOption = this.interfaceOption.Where(o => o.OperateType == "editRow").First();//更行API配置
            deleteOption = this.interfaceOption.Where(o => o.OperateType == "deleteRow").First();//删除API配置

            //查询执行中的事件
            OnQueryEvent += Interface_Business_OnQueryEvent; ;
            //查询执行前的事件
            BeforeQueryEvent += Interface_Business_BeforeQueryEvent;
            //执行非查询请求中的事件
            OnNoQueryEvent += Interface_Business_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void Interface_Business_OnNoQueryEvent(object sender, NoQueryEventArgs noQueryEventArgs)
        {
            //API请求是否成功
            noQueryEventArgs.Success = noQueryEventArgs.Result["success"].ToString().ToBool();
        }


        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void Interface_Business_BeforeQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            if (queryEventArgs.Page.Filters.IsNullOrEmpty() && !Filters.IsNullOrEmpty())
            {
                queryEventArgs.Page.Filters = Filters;
            }
        }


        /// <summary>
        /// 查询执行中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void Interface_Business_OnQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //是否查询完成
            if (queryEventArgs.Result["data"]["rows"].ToList().Count == 0)
            {
                queryEventArgs.Page.Complete = true;
            }
            //向总行中添加新的行
            queryEventArgs.Rows.AddRange(queryEventArgs.Result["data"]["rows"].ToList());
            //获取总页数
            queryEventArgs.Page.Total = queryEventArgs.Result["data"]["total"].ToString().ToInt();
            //获取查询成功标志
            queryEventArgs.Success = queryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 新增更新表
        /// </summary>
        public async void ExecuteInterface()
        {

            try
            {
                //获取退货表的开始日期
                string dateForm = DateTime.Now.AddMonths(-1).ToString("yyyy-MM") + "-01";
                int days = (DateTime.Now - dateForm.ToDateTime()).Days;
                List<string> dateList = new List<string>();
                //获取所有需要计算的数据的日期
                while (days != -1)
                {
                    dateList.Add(DateTime.Now.AddDays(-days).ToString("yyyy-MM-dd"));
                    days--;
                }



                //获取销售目标报表
                OL_SalTargetInterfaceBusiness salTarget = new OL_SalTargetInterfaceBusiness();
                List<SalTarget> salTargets = await salTarget.QueryAsync<SalTarget>(salTarget.queryOption, salTarget.tableField, salTarget.SqlDb);
                //将列表文本数据转换成列表对象
                if (salTargets.Count > 0 && !salTargets.IsNullOrEmpty())
                {
                    foreach (var item1 in salTargets)
                    {
                        //SKU
                        List<AssTable> table = item1.SKU.ToObject<List<AssTable>>();
                        if (!table.IsNullOrEmpty() && table.Count > 0) item1.SKU_T = table[0];
                        //产品类型
                        table = item1.ProType.ToObject<List<AssTable>>();
                        if (!table.IsNullOrEmpty() && table.Count > 0) item1.ProType_T = table[0];
                        //亚马逊店铺
                        table = item1.Store.ToObject<List<AssTable>>();
                        if (!table.IsNullOrEmpty() && table.Count > 0) item1.Store_T = table[0];
                        //部门责任人
                        List<Choice> choice = item1.DepResponsible.ToObject<List<Choice>>();
                        if (!choice.IsNullOrEmpty() && choice.Count > 0) item1.DepResponsible_T = choice[0];
                        //销售人员
                        choice = item1.SalPerson.ToObject<List<Choice>>();
                        if (!choice.IsNullOrEmpty() && choice.Count > 0) item1.SalPerson_T = choice[0];
                    }
                }
                //获取亚马逊报表
                OL_AmazonRepInterfaceBusiness amazonRep = new OL_AmazonRepInterfaceBusiness();
                amazonRep.Filters.Add(
            new OL_FilterDTO() { ControlId = "6777a8229e0bc69bf1693443", DataType = 29, SpliceType = 1, FilterType = 8, Value = "" }
            //new OL_FilterDTO() { ControlId = "661d1c34387bc49b7a55d06e", DataType = 15, SpliceType = 1, FilterType = 14, Value = "2024-11-24" }
                );
                List<AmazonRep> amzs = await amazonRep.QueryAsync<AmazonRep>(amazonRep.queryOption, amazonRep.tableField, amazonRep.SqlDb);
                foreach (var item1 in amzs)
                {
                    //销售人员
                    List<Choice> choice = item1.SalPerson.ToObject<List<Choice>>();
                    item1.SalPerson_T = !choice.IsNullOrEmpty() && choice.Count > 0 ? choice[0] : new Choice() { fullname = "" };
                    //产品品类
                    //List<AssTable> table = item1.ProType.ToObject<List<AssTable>>();
                    //item1.ProType_T = !table.IsNullOrEmpty() && table.Count > 0 ? table[0] : new AssTable() { name = "" };
                    //SKU
                    List<AssTable> table = item1.SKU.ToObject<List<AssTable>>();
                    item1.SKU_T = !table.IsNullOrEmpty() && table.Count > 0 ? table[0] : new AssTable() { name = "" };
                    //品牌
                    //table = item1.Brand.ToObject<List<AssTable>>();
                    //item1.Brand_T = !table.IsNullOrEmpty() && table.Count > 0 ? table[0] : new AssTable() { name = "" };
                    //亚马逊店铺
                    //table = item1.Store.ToObject<List<AssTable>>();
                    //item1.Store_T = !table.IsNullOrEmpty() && table.Count > 0 ? table[0] : new AssTable() { name = "" };
                    item1.Store = item1.Store;
                    item1.ID = item1.SKU_T.name + item1.Store + item1.Date;

                }

                //防止统同一天有多行相同的SKU出现，将多行汇总成一行
                List<AmazonRep> amazonReps = amzs.GroupBy(x => x.ID).Select(x =>
                {

                    AmazonRep amz = x.First().DeepClone();
                    double dayVolume = x.Sum(x => x.ThatDayVolume.ToInt());
                    double daySale = Math.Round(x.Sum(x => Math.Round(x.ThatDaySales.ToDouble(), 2)), 2);
                    double dayAdv = Math.Round(x.Sum(x => Math.Round(x.ThatDayAdv.ToDouble(), 2)), 2);
                    double dayReturn = Math.Round(x.Sum(x => Math.Round(x.ThatDayReturn.ToDouble(), 2)), 2);
                    amz.ThatDayVolume = dayVolume.ToString();
                    amz.ThatDaySales = daySale.ToString();
                    amz.ThatDayAdv = dayAdv.ToString();
                    amz.ThatDayACOS = daySale == 0 || dayAdv == 0 ? "0" : (dayAdv / daySale * 100).ToString("0.00", CultureInfo.InvariantCulture);
                    amz.ThatDayReturn = dayReturn.ToString();
                    amz.ThatDayReturnRate = dayReturn == 0 || dayVolume == 0 ? "0" : (dayReturn / dayVolume * 100).ToString("0.00", CultureInfo.InvariantCulture);
                    return amz;

                }).ToList();

                //获取源数据
                List<SalDaily> sourceData = new List<SalDaily>();

                #region 生成每一行数据，用每天的亚马逊报表数据，将月目标数据分解成每天的数据，
                if (salTargets.Count > 0 && amazonReps.Count > 0)
                {

                    //默认了目标数据为当月数据
                    foreach (var T in salTargets)
                    {
                        if (T.SKU == "FS07B1SWD")
                        {
                            var ww = "";
                        }
                        //获取每行目标的月份
                        string tarMonth = T.StartDate.ToDateTime().ToString("yyyy-MM");

                        //获取与当前目标SKU，店铺，月份相符的亚马逊报表数据
                        List<AmazonRep> SUK_EveryDay = amazonReps.Where(x =>
                        {
                            bool isOK = false;
                            //获取亚马逊报表当前数据的月份
                            string month = x.Date.ToDateTime().ToString("yyyy-MM");
                            //不筛选SKU为空的项
                            if (x.SKU_T.IsNullOrEmpty() || T.SKU_T.IsNullOrEmpty() || x.Store.IsNullOrEmpty() || T.Store_T.IsNullOrEmpty()) isOK = false;
                            //获取SKU，店铺，月份相等的日数据
                            else if (x.SKU_T.name == T.SKU_T.name && x.Store == T.Store_T.name && month == tarMonth) isOK = true;
                            return isOK;
                        }).ToList();


                        //设置公共数据
                        SalDaily salDaily = new SalDaily();
                        salDaily.DepResponsible = T.DepResponsible_T.IsNullOrEmpty() ? "[]" : T.DepResponsible_T.accountId;
                        salDaily.DepResponsible_T = T.DepResponsible_T.IsNullOrEmpty() ? "[]" : T.DepResponsible_T.fullname;
                        salDaily.SalPerson = T.SalPerson_T.IsNullOrEmpty() ? "[]" : T.SalPerson_T.accountId;
                        salDaily.SalPerson_T = T.SalPerson_T.IsNullOrEmpty() ? "[]" : T.SalPerson_T.fullname;
                        salDaily.SKU = T.SKU_T.IsNullOrEmpty() ? "[]" : T.SKU_T.sid;
                        salDaily.SKU_T = T.SKU_T.IsNullOrEmpty() ? "[]" : T.SKU_T.name;
                        salDaily.Store = T.Store_T.IsNullOrEmpty() ? "[]" : T.Store_T.sid;
                        salDaily.Store_T = T.Store_T.IsNullOrEmpty() ? "[]" : T.Store_T.name;
                        salDaily.ProType = T.ProType_T.IsNullOrEmpty() ? "[]" : T.ProType_T.sid;
                        salDaily.ProType_T = T.ProType_T.IsNullOrEmpty() ? "[]" : T.ProType_T.name;
                        salDaily.Department = T.Department.IsNullOrEmpty() ? "" : T.Department;

                        salDaily.TargetSalVolume = T.TargetVolume.IsNullOrEmpty() ? "0" : T.TargetVolume;
                        salDaily.TargetSal = T.TargetSales.IsNullOrEmpty() ? "0" : T.TargetSales;
                        salDaily.TargetAdv = T.TargetAdv.IsNullOrEmpty() ? "0" : T.TargetAdv;
                        salDaily.TargetACOS = T.TargetACOS.IsNullOrEmpty() ? "0" : T.TargetACOS;


                        //月销量
                        double monthVolume = SUK_EveryDay.Sum(x => x.ThatDayVolume.ToDouble());
                        //月销售额
                        double monthSale = SUK_EveryDay.Sum(x => x.ThatDaySales.ToDouble());
                        //月广告费
                        double monthAdv = SUK_EveryDay.Sum(x => x.ThatDayAdv.ToDouble());
                        //目标销售额
                        double targetSal = salDaily.TargetSal.ToDouble();
                        salDaily.MonthSalVolume = monthVolume.ToString();
                        salDaily.MonthSal = monthSale.ToString();
                        salDaily.MonthAdv = monthAdv.ToString();
                        salDaily.MonthACOS = monthSale == 0 || monthAdv == 0 ? "0" : (monthAdv / monthSale * 100).ToString("0.00", CultureInfo.InvariantCulture);

                        salDaily.Achievement = monthSale == 0 || targetSal == 0 ? "0" : (monthSale / targetSal * 100).ToString("0.00", CultureInfo.InvariantCulture);

                        //创建每一行数据
                        var TEST1 = dateList.Where(x => x.ToDateTime().ToString("yyyy-MM") == tarMonth);
                        var countDays = SUK_EveryDay.Select(x => x.Date.ToDateTime().ToString("yyyy-MM-dd"));
                        foreach (var item1 in dateList.Where(x => x.ToDateTime().ToString("yyyy-MM") == tarMonth))
                        {
                            if (!countDays.Contains(item1))
                            {
                                AmazonRep rep = new AmazonRep();
                                rep.Date = item1;
                                rep.ThatDayVolume = "0";
                                rep.ThatDaySales = "0";
                                rep.ThatDayAdv = "0";
                                rep.ThatDayACOS = "0";
                                SUK_EveryDay.Add(rep);
                            }
                        }

                        foreach (var D in SUK_EveryDay)
                        {
                            SalDaily salDaily_d = salDaily.DeepClone();
                            salDaily_d.Date = D.Date;
                            salDaily_d.DateSalVolume = D.ThatDayVolume;
                            salDaily_d.DateSal = D.ThatDaySales;
                            salDaily_d.DateAdv = D.ThatDayAdv;
                            salDaily_d.DateACOS = D.ThatDayACOS;
                            sourceData.Add(salDaily_d);
                        }
                    }


                }
                #endregion

                //设置ID
                sourceData.ForEach(x => x.ID = x.SKU_T + x.Store_T + x.Date);
                var t = sourceData.GroupBy(x => x.ID).Where(x => x.Count() > 1);

                //获取目标数据
                List<SalDaily> targetData = new List<SalDaily>();//目标据集合
                Filters.Clear();
                Filters.Add(
                new OL_FilterDTO() { ControlId = "67418aec68763d2a95aca751", DataType = 15, SpliceType = 1, FilterType = 14, Value = DateTime.Now.AddMonths(-1).ToString("yyyy-MM") + "-1" }
            );
                targetData = await QueryAsync<SalDaily>(queryOption, tableField, SqlDb);
                foreach (var item1 in targetData)
                {
                    //销售人员
                    List<Choice> choice = new List<Choice>();
                    if (!item1.SalPerson.IsNullOrEmpty()) choice = item1.SalPerson.ToObject<List<Choice>>();
                    if (choice.Count > 0 && !choice.IsNullOrEmpty()) item1.SalPerson = choice[0].accountId;
                    //部门管理
                    if (!item1.DepResponsible.IsNullOrEmpty()) choice = item1.DepResponsible.ToObject<List<Choice>>();
                    if (choice.Count > 0 && !choice.IsNullOrEmpty()) item1.DepResponsible = choice[0].accountId;
                    //产品品类
                    List<AssTable> table = new List<AssTable>();
                    if (!item1.ProType.IsNullOrEmpty()) table = item1.ProType.ToObject<List<AssTable>>();
                    if (table.Count > 0 && !table.IsNullOrEmpty()) item1.ProType = table[0].sid;
                    //SKU
                    if (!item1.SKU.IsNullOrEmpty()) table = item1.SKU.ToObject<List<AssTable>>();
                    if (table.Count > 0 && !table.IsNullOrEmpty()) item1.SKU = table[0].sid;
                    //亚马逊店铺
                    if (!item1.Store.IsNullOrEmpty()) table = item1.Store.ToObject<List<AssTable>>();
                    if (table.Count > 0 && !table.IsNullOrEmpty()) item1.Store = table[0].sid;
                }

                if (this.State > 0 && sourceData.Count > 0)
                {
                    //更新
                    #region
                    List<SalDaily> updataItem = sourceData.Intersect(targetData, new ComparerFromKeys<SalDaily>(Keys, "RowId")).ToList();//获取交集(更新项)
                    List<OL_RowDTO> updataData = ConvertOL_Row(updataItem, tableField);//需要更新的数据集合
                    ExecuteNoQuery<OL_RowDTO>(updataData, upDateOption, SqlDb);//执行更新
                    #endregion

                    //新增
                    #region
                    List<SalDaily> insertItem = sourceData.Except(targetData, new ComparerFromKey<SalDaily>(indexFields.First(), "RowId")).ToList();//获取源数据对目标数据的差集(新增项)
                    List<OL_RowDTO> insertData = ConvertOL_Row(insertItem, tableField);//需要新增的数据集合
                    ExecuteNoQuery<OL_RowDTO>(insertData, insertOption, SqlDb);//执行插入行
                    #endregion

                    //删除
                    #region
                    List<SalDaily> deleteItem = targetData.Except(sourceData, new ComparerFromKey<SalDaily>(indexFields.First(), "RowId")).ToList();//获取目标数对据源数据的差集(删除项)
                    //获取有重复的项
                    List<SalDaily> repeatItem = targetData.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                    //将重复的项也一起加入删除的列表
                    deleteItem.AddRange(repeatItem);
                    //筛选出删除列表中重复的项
                    var temp = deleteItem.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                    deleteItem.AddRange(temp);
                    List<OL_RowDTO> deleteData = ConvertOL_Row(deleteItem, tableField);//需要删除的数据集合
                    ExecuteNoQuery<OL_RowDTO>(deleteData, deleteOption, SqlDb);//执行删除行
                    #endregion
                }
                else
                {
                    throw new NotImplementedException("目标/源查询无数据无法执行接口!!");

                }
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }






        /// <summary>
        /// 将源数据根据字典映射关系转换成OL_RowDTO
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="sourceData">源数据</param>
        /// <param name="map">Key为目标字段名称，Value为源字段名称</param>
        /// <returns></returns>
        public List<OL_RowDTO> ConvertOL_Row<T>(List<T> sourceData, Dictionary<string, string> map)
        {
            List<OL_RowDTO> list = new List<OL_RowDTO>();
            object rowId;
            foreach (var item in sourceData)
            {
                rowId = item.GetPropertyValue("RowId");
                //需要新增的数据
                OL_RowDTO row = new OL_RowDTO() { RowId = rowId.IsNullOrEmpty() ? null : rowId.ToString(), Controls = new List<Control>() };
                foreach (var c in map)
                {
                    //判断对象的字段是否存在
                    if (item.ContainsProperty(c.Value))
                    {
                        //存在则添加数据
                        row.Controls.Add(new Control() { ControlId = c.Key, Value = item.GetPropertyValue(c.Value) });
                    }
                }
                list.Add(row);
            }
            return list;
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }



}
